<template>
	<div class="main">
		<div style="width:50%;float:left">
			<div class="custom-styles">
				<span class="font14">{{ type == 'edit' ? '编辑教材' : '新增教材' }}</span>
			</div>
			<el-form ref="formRef" :model="form" label-width="80px">
				<div class="mc-item ct-item">
					<el-form-item label="封面" prop="coverUrl">
						<pro-upload-img
							:fileList="fileList"
							:maxSize="1"
							accept=".jpg,.png"
							tip="图片格式，不超过2MB"
							@success="handleSuccess"
							@error="handleError"
						/>
					</el-form-item>
					<el-form-item label="名称" prop="name"
								  :rules="{required: true, message: '请输入名称', trigger: 'change'}">
						<el-input v-model="form.name" />
					</el-form-item>
<!--					<el-form-item label="编号" prop="bookNo">
						<el-input-number placeholder="第1位代表教材学段，2-3位代表教材系列，4-5位代表课本" :max="10000000"
										 v-model="form.bookNo" controls-position="right" />
					</el-form-item>-->
					<el-form-item label="学段" prop="stage"
								  :rules="{required: true, message: '请选择学段', trigger: 'change'}">
						<el-select v-model="form.stage" @change="changeStage">
							<el-option v-for="item in options" :key="item.key" :label="item.value"
									   :value="item.key"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="年级" prop="grade" v-if="form.stage"
								  :rules="{required: true, message: '请选择学段', trigger: 'change'}">
						<el-select v-model="form.grade">
							<el-option v-for="item in gradeOptions" :key="item.key" :label="item.value"
									   :value="item.key"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="版本" prop="seriesNo" v-if="form.stage"
								  :rules="{required: true, message: '请选择版本', trigger: 'change'}">
						<el-select v-model="form.seriesNo">
							<el-option v-for="item in versionOptions" :key="item.key" :label="item.value"
									   :value="item.key"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="册次" prop="semester"
								  :rules="{required: true, message: '请选择册次', trigger: 'change'}">
						<el-select v-model="form.semester">
							<el-option v-for="item in volumeOptions" :key="item.key" :label="item.value"
									   :value="item.key"></el-option>
						</el-select>
					</el-form-item>
<!--					<el-form-item label="排序号" prop="orderNum">
						<el-input-number :min="1" :max="10000000" v-model="form.orderNum" controls-position="right" />
					</el-form-item>-->
					<div style="text-align:center;margin-top: 60px">
						<el-button type="primary" @click="saveForm">保 存</el-button>
					</div>
				</div>
			</el-form>
		</div>

		<div style="width:50%;float:left" v-if="type=='edit'">
			<el-collapse v-model="activeNames">
				<el-collapse-item title="章节管理" name="chapters">
					<el-button type="primary" link @click="addChapter" size="small" class="edit-course">+新增教材章</el-button>
					<div class="mc-item mc-item2">
						<tree
							:data="chapters.list"
							:bookNo="form.bookNo"
							tab="textbook"
							:maxLevel="3"
							@node-added="handleNodeAdded"
							@node-updated="handleNodeUpdated"
							@node-deleted="handleNodeDeleted"
							ref="treeRef"
						></tree>
					</div>
				</el-collapse-item>
			</el-collapse>
		</div>
	</div>
</template>
<script setup lang="ts">
import tree from '../../../plugins/tree/index.vue';
import ProUploadImg from '/#/upload/index.vue';
import { onMounted, reactive, ref, nextTick, watch } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import {
	getStageCombobox,
	getGradeCombobox,
	getSeriesCombobox,
	getSemesterCombobox,
	getSeriesTree,
	addTextbook,
	getComboboxByStageId,
	getSeriesComboboxByStage,
	modifyTextbook,
	getBookChapterTreeByBookNo,
	addBookChapter,
	modifyBookChapter, delBookChapterById
} from '/@/api/home/index';
import { useRoute } from 'vue-router';
import { useCool } from '/@/cool/hooks';

const { router } = useCool();
const route = useRoute();
const formRef = ref<FormInstance>();
let type = ref('');
const activeNames = ref('chapters');
const props = defineProps({
	type: String
});
let chapters = reactive({
	list: []
});
let options = ref([]);
const treeRef = ref<InstanceType<typeof tree>>()
let gradeOptions = ref([]);//年级
let volumeOptions = ref([]);//册次
let versionOptions = ref([]);//版本
let seriesOptions = ref([]);//学科
const fileList = ref([]);
let form = reactive({
	id: '',
	grade: '',
	stage: '',
	bookNo: null,
	coverUrl: 'http://www.dzkbw.com/books/rjb/shuxue/ws9s/coverbig.jpg',
	semester: '',
	orderNum: null,
	seriesNo: '',
	name: ''
});
const saveForm = () => {
	formRef.value?.validate(async valid => {
		if (valid) {
			let res = (type.value == 'add')?await addTextbook(form):await modifyTextbook(form);
			if (res.code==200) {
				ElMessage.success((type.value == 'edit' ? '编辑教材' : '新增教材') + '成功');
				setTimeout(async () => {
					await router.push({
						path: '/textbook/book'
					})
				}, 500);
			}
		}
	});
};
const queryTree = async () => {
	if (type.value === 'edit') {
		const parsedQuery = {
			...route.query,
			grade: Number(route.query.grade),
			stage: Number(route.query.stage),
			semester: Number(route.query.semester),
			seriesNo: Number(route.query.seriesNo)
		};

		fileList.value.push({ url: parsedQuery.coverUrlShow });
		//form = Object.assign({}, form, parsedQuery);
		Object.assign(form, parsedQuery)
		let treeList = await getBookChapterTreeByBookNo(form.bookNo);
		chapters.list = treeList.data;
	}
}
onMounted(async () => {
	type.value = route.query.type;
	await queryTree();
	let res = await getStageCombobox();
	options.value = res.data;
	let res_ = await getGradeCombobox();
	gradeOptions.value = res_.data;
	let res__ = await getSeriesCombobox();
	versionOptions.value = res__.data;
	let res___ = await getSemesterCombobox();
	volumeOptions.value = res___.data;
	let res____ = await getSeriesTree();
	seriesOptions.value = res____.data;
});

const addChapter = async () => {
	if (treeRef.value) {
		treeRef.value.appendRoot()
	}
};
const handleNodeAdded = async (newNode) => {
	let res = await addBookChapter(newNode);
	if (res.code == 200) {
		newNode.id = res.data;
	} else {
		treeRef.value?.rollbackAddedNode()
	}
};
const handleNodeUpdated = async (node) => {	// 调用修改接口
	let res = await modifyBookChapter(node);
	if (res.code !== 200) {
		treeRef.value?.rollbackNode();
	}
};
const changeStage = () => {
	form.grade = '';
	form.seriesNo = '';
	form.semester = '';
}
const handleNodeDeleted = async (id) => {
	await delBookChapterById(id)
}
const handleSuccess = (response, uploadFile, uploadFiles) => {
	form.coverUrl = response.name;
}
const handleError = () => {

}
watch(() => form.stage, async (newVal) => {
	if (newVal) {
		let res = await getComboboxByStageId(newVal);
		gradeOptions.value = res.data;
		let res_ = await getSeriesComboboxByStage(newVal);
		versionOptions.value = res_.data;
	}
});
</script>
